module Cip
  class PagesController < ApplicationController
    layout "../cip/pages/layout"

    def index
      render "cip/pages/static/index"
    end

    def category
      render_category Category.search_by!(params[:category_id])
    end

    def category_first_child
      category = Category.search_by!(params[:category_id]).children.first!
      redirect_to cip_category_path(category)
    end

    def show
      render_page Page.find(params[:id])
    end

    def category_page
      page = Category.search_by!(params[:category_id]).pages.first!
      redirect_to cip_page_path(page)
    end

    def static
      render "cip/pages/static/#{params[:page_id]}"
    end

    rescue_from ActionView::MissingTemplate, ActiveRecord::RecordNotFound do |exception|
      Rails.logger.error(exception)
      render file: Rails.root.join('public/404.html'), status: :not_found, layout: false
    end

    private

    def render_page page, category = nil
      @page = page
      @category = category || @page.category

      @page.update_attributes(view_count: (@page.view_count || 0) + 1)
      if template = @page.template.presence || @category.page_template
        Rails.logger.info "  Rendering with template #{template}"
        render "cip/pages/show/#{template}"
      else
        render 'show'
      end
    end

    def render_category category
      @category = category
      @pages = @category.children_pages

      if template = @category.template
        Rails.logger.info "  Rendering with template #{template}"
        render "cip/pages/index/#{template}"
      else
        render 'index'
      end
    end
  end
end
